package nl.hva.three2learn.dao;

import java.util.Date;
import java.util.List;

import nl.hva.three2learn.model.Message;
import nl.hva.three2learn.model.User;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class MessageDaoImpl implements MessageDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public List<Message> findBySenderAndReceiver(User sender, User receiver) {

		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Message m " + 
									  "where sender = :sender and " + 
									  "receiver = :receiver");
		
		q.setEntity("sender", sender);
		q.setEntity("receiver", receiver);
		
		@SuppressWarnings("unchecked")
		List<Message> messages = q.list();
		session.getTransaction().commit();
		return messages;
	}
	
	@Override
	public List<Message> findByStartDate(long senderId, long receiverId, Date start) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Message m where m.sender = :sender " +
									  "and m.receiver = :receiver");
		
		q.setLong("sender", senderId);
		q.setLong("receiver", receiverId);
		
		@SuppressWarnings("unchecked")
		List<Message> messages = q.list();
		
		session.getTransaction().commit();
		
		return messages;
	}

	@Override
	public void save(Message message) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(message);
		session.getTransaction().commit();
		//session.close();
	}
	
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}
}
